// pages/task_list/task_list.js
let listBehavior = require('../../behavior/list')

Page({
  behaviors: [listBehavior,],

  /**
   * 页面的初始数据
   */
  data: {
    isLoading: false,

    tabList: [
      // { title: '全部', name: '', },
      { title: '待领取', name: '', },
      { title: '待执行', name: '', },
      { title: '执行中', name: '', },
      { title: '已执行', name: '', },
    ],
    tabActive: 0,

    colList: [
      { key: 'siji1xingming', label: '司机1', tabActive: 0 },
      { key: 'siji2xingming', label: '司机2', tabActive: 0 },
      { key: 'chepaihaoma', label: '车牌号码', tabActive: 0 },
      { key: 'quchengqidian', label: '上车点' },
      { key: 'quchengqidi', label: '目的地', },
      { key: 'chufa_time', label: '出发时间', },
      { key: 'renwunarong', label: '任务内容', },

    ],
    tableList: [],
    cancelOrderId: '',
    cancelIdx: '',
    cancelShow: false,
    cancelReason: '',
    flag: false,
    detl: null,
  },

  onTabChange (e) {
    let { idx, } = e.currentTarget.dataset,
      { isLoading } = this.data
    if (isLoading) return
    this.setData({
      tabActive: idx,
      tableList: []
    })
    this.getFirstPage()
  },
  onNavTo (e) {
    let { url, } = e.currentTarget.dataset
    wx.navigateTo({
      url,
    })
  },
  onDetl (e) {
    let { orderid } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/repairPages/task_detl/task_detl?orderId=${orderid}`,
    })
  },
  showFlag () {
    this.setData({ flag: !this.data.flag })
  },
  onComplete (e) {
    let { row_id } = e.currentTarget.dataset
    let that = this;
    wx.showModal({
      content: '确认是否完成任务？',
      success: (res) => {
        if (res.confirm) { // 发送请求
          let postData = {
            "table": {
              "table_id": "v_zuchepaichedanmingxibiao",
              "entitys": [{
                "entity": {
                  "paichedanzhuangtaimingchen": "已完成",
                  "paichedanzhuangtaibianhao": "4",
                  row_id,
                  'xuanzepaichedanzhuangtai': 5
                },
                "details": []

              }]
            }
          }
          wx.$post(3, 'DynamicUpdate/dynamic_update_v3', postData).then(res => {
            if (res.response.errcode != 0) return wx.$toast(res.response.errmsg);
            wx.$toast('提交成功，已完成任务', 1500).then(() => {
              that.getRefreshPage()
            })
          })
        }
      },
    })
  },
  onToggleFlag (e) {
    let { row_id } = e.currentTarget.dataset
    let that = this;
    let detl = that.data.tableList.filter(obj => {
      return obj.row_id === row_id
    })
    if (detl.length > 0) {
      this.setData({ detl: detl[0], flag: true })
    }
    // wx.showModal({
    //   content: '确认是否开启任务？',
    //   success: (res) => {
    //     if (res.confirm) { // 发送请求
    //       let postData = {
    //         "table": {
    //           "table_id": "v_zuchepaichedanmingxibiao",
    //           "entitys": [{
    //             "entity": {
    //               "paichedanzhuangtaimingchen": "已发车",
    //               "paichedanzhuangtaibianhao": "2",
    //               row_id,
    //               'xuanzepaichedanzhuangtai': 3
    //             },
    //             "details": []
    //           }]
    //         }
    //       }
    //       wx.$post(3, 'DynamicUpdate/dynamic_update_v3', postData).then(res => {
    //         if (res.response.errcode != 0) return wx.$toast(res.response.errmsg);
    //         wx.$toast('已开启任务', 1500).then(() => {
    //           that.getRefreshPage()
    //         })
    //       })
    //     }
    //   },
    // })
  },
  async onGetPostrData (e) {
    let { lichengbiao, kaishilichengshu, jieshulichengshu, row_id } = e.detail;
    let postData = {}, that = this;
    if (this.data.tabActive == 1) {
      postData = {
        kaishilichengshu,
        kaishilichengbiaozhao: lichengbiao,
        "paichedanzhuangtaimingchen": "已发车",
        "paichedanzhuangtaibianhao": "2",
        row_id,
        'xuanzepaichedanzhuangtai': 3
      }
    } else {
      postData = {
        jieshulichengshu,
        jieshulichengbiaozhao: lichengbiao,
        "paichedanzhuangtaimingchen": "已完成",
        "paichedanzhuangtaibianhao": "4",
        row_id,
        'xuanzepaichedanzhuangtai': 5
      }
    }
    let dataObj = {
      "table": {
        "table_id": "v_zuchepaichedanmingxibiao",
        "entitys": [{
          "entity": postData,
          "details": []
        }]
      }
    }
    wx.showLoading({ title: "正在提交" });
    wx.$post(3, 'DynamicUpdate/dynamic_update_v3', dataObj).then(res => {
      wx.hideLoading();
      if (res.response.errcode != 0) return wx.$toast(res.response.errmsg);
      wx.$toast(that.data.tabActive == 1 ? "提交成功,已开启任务" : '提交成功,已完成任务', 1500).then(() => {
        that.setData({ flag: false })
        that.getRefreshPage()
      })
    })
  },
  // 230331 确认任务
  // onConfirmTask(e) {
  //   wx.showModal({
  //     content: '确定确认任务吗？',
  //     success: (res) => {
  //       if (res.confirm) { // 发送请求

  //       }
  //     },
  //   })
  // },
  // 出车
  // onGoOutTask (e) {
  //   this.onToggleFlag(e)
  // },
  // 抵达上车点
  // onArriveTripPoint (e) {
  //   this.onToggleFlag(e)
  // },
  // 抵达下车点
  // onArriveDestPoint (e) {
  //   this.onToggleFlag(e)
  // },
  // 车场时间
  // onArriveParkPoint (e) {
  //   wx.showModal({
  //     content: '确定确认收车吗？',
  //     success: (res) => {
  //       if (res.confirm) { // 发送请求

  //       }
  //     },
  //   })
  // },

  //领取任务
  onReceiveTask (e) {
    let that = this;
    let { row_id } = e.target.dataset;
    if (row_id) {
      wx.showModal({
        content: '确定领取该任务吗？',
        success: (res) => {
          if (res.confirm) { // 发送请求
            wx.$post(5, 'BC/DispatchTaskDriverReply', { dispatch_id: row_id, is_accepted: true }).then(res => {
              if (res.response.errcode != 0) return wx.$toast(res.response.errmsg);
              wx.$toast(res.errmsg, 1500).then(() => {
                that.getRefreshPage()
              })
            })
          }
        },
      })
    }
  },
  //拒绝任务
  onRefuseTask (e) {
    let { row_id } = e.target.dataset;
    let that = this;
    if (row_id) {
      wx.showModal({
        content: '确定拒绝该任务吗？',
        success: (res) => {
          console.log(res)
          if (res.confirm) { // 发送请求
            wx.$post(5, 'BC/DispatchTaskDriverReply', { dispatch_id: row_id, is_accepted: false }).then(res => {
              if (res.response.errcode != 0) return wx.$toast(res.response.errmsg);
              wx.$toast(res.errmsg, 1500).then(() => {
                that.getRefreshPage()
              })
            })
          }
        },
      })
    }
  },
  onNextPage () {
    this.getNextPage()
  },
  // 接口
  getDataList () {
    let { page, limit, tabActive, tableList, } = this.data;
    console.log(this.data)
    this.setData({
      isLoading: true,
    })
    wx.showLoading()
    let postData = {};
    let CompareValueStatus = tabActive == 0 ? '待接受' : '已接受'
    let wherers = [{ "CompareWith": "v_zuchepaichedanmingxibiao.Order_No", "Operator": "is not null", "CompareValue": "", "or": 0 }]
    // 默认 待接收任务，且 司机1 和 司机2是否有当前账号判断
    if (tabActive == 0) { // 待领取任务
    }
    // 判断接受状态后且状态已更改完待派车 待执行
    if (tabActive == 1) {
      wherers.push({ "CompareWith": "v_zuchepaichedanmingxibiao.xuanzepaichedanzhuangtai", "Operator": "=", "CompareValue": "1", "or": 0 })
    }
    // 判断接受状态后且状态已更改完已发车  执行中
    if (tabActive == 2) {
      wherers.push({ "CompareWith": "v_zuchepaichedanmingxibiao.xuanzepaichedanzhuangtai", "Operator": "=", "CompareValue": "3", "or": 0 })
    }
    if (tabActive == 3) { // 已执行  订单已完成
      wherers.push({ "CompareWith": "v_zuchepaichedanmingxibiao.xuanzepaichedanzhuangtai", "Operator": "=", "CompareValue": "5", "or": 0 })
    }
    let childrenTwo = [
      {
        "CompareWith": "v_zuchepaichedanmingxibiao.siji2yinyong",
        "Operator": "=",
        "CompareValue": wx.getStorageSync('driver_row_id'),
        "or": 0
      },
      {
        "CompareWith": "v_zuchepaichedanmingxibiao.assistant_driver_accept_state",
        "Operator": "=",
        "CompareValue": CompareValueStatus,
        "or": 0
      }
    ],
      childrenOne = [{
        "CompareWith": "v_zuchepaichedanmingxibiao.siji1yinyong",
        "Operator": "=",
        "CompareValue": wx.getStorageSync('driver_row_id'),
        "or": 0
      }, {
        "CompareWith": "v_zuchepaichedanmingxibiao.main_driver_accept_state",
        "Operator": "=",
        "CompareValue": CompareValueStatus,
        "or": 0
      }];
    postData = {
      "oby": "v_zuchepaichedanmingxibiao.row_id", "table_id": "v_zuchepaichedanmingxibiao", "page": page, "limit": limit,
      "SearchWhere": { filters: wherers, type: 'and', children: [{ filters: childrenOne, type: 'or' }, { filters: childrenTwo, type: 'or' }] }
    }
    wx.$post(3, 'DynamicQuery/query_dynamic_v3', postData).then(res => {
      wx.hideLoading();
      this.setData({ isLoading: false, })
      if (res.response.errcode != 0) return wx.$toast(res.response.errmsg)
      let { row, total, } = res.data,
        status = {
          0: { name: '待领取', cls: 'red', },
          1: { name: '待执行', cls: 'red', },
          2: { name: '执行中', cls: 'blue', },
          4: { name: '已执行', cls: 'black', },
        }
      row.forEach(row => {
        let statusObj = status[tabActive] || {}
        row.status = statusObj.name || ''
        row.cls = statusObj.cls || ''
        row.tabActive = tabActive
        row.chufa_time = row.kaishiriqi ? `${row.kaishiriqi ? row.kaishiriqi.split(' ')[0] : ''} ${row.kaishishijian ? row.kaishishijian.split(' ')[1] : ''}` : ''
      })
      if (page !== 1) row = [...tableList, ...row,]
      this.setData({
        tableList: row,
        page,
        total,
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow () {
    this.getDataList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage () {

  },
})
